// 投递报名表
const baseUrl = 'https://gsdse.cn/api/KJRecruit';
const app = getApp();
const db = wx.cloud.database();
const _ = db.command
import extension from '../../utils/getExtensionName/getExtensionName.js'
var myDate = new Date();
var timestamp = Date.parse(new Date());
var date = new Date(timestamp);
var Year = date.getFullYear();
var data_now = Year; //当前年份
Page({
  /**
   * 页面的初始数据
   */
  data: {
    willingFirst: ['请选择', '秘书处', '网络研发部', "影视部", '动画部', "PC技术部", "新媒体运营部", 'UI设计部', ],
    willingSecond: ["无", '秘书处', '网络研发部', "影视部", '动画部', "PC技术部", "新媒体运营部", 'UI设计部', ],
    willingFirstName: '', //第一志愿名称
    willingSecondName: '', //第二志愿名称
    willingStatus: false, //志愿填写情况
    backgroundImage: {
      type: String,
      value: 'https://636c-cloud1-8g54d6xb74e96e7d-1311924947.tcb.qcloud.la/images/background_img.svg?sign=8a7edc744f39096f556f257aa0a1a777&t=1657022356'
    },
    wordIcon: 'http://frontend.gsdse.cn/gsdkj-recruit/static/img/images/word.svg',
    pdfIcon: 'http://frontend.gsdse.cn/gsdkj-recruit/static/img/images/pdfIcon.svg',
    pickStatus: '',
    temperFile: {}, //临时保存的文件路径对象
    temperFilePath: '',
    postFilename: '文件名',
    postFilenameModified: '文件名', //处理后的文件名
    postFilesize: '23kb',
    fileRecord: 0, //查询文件记录的结果
    onlineFilepath: '', //上传文件后返回的fileid,
    _openid: '',
    willingFirst_index: '',
    willingSecond_index: '',
    extensionName: '',
    onlineFilename: '', //查询的表中的文件名,
    temperOnlinefileID: '', //这个变量用来暂时储存查询时获得的表中文件ID，用于上传文件名不重复时删除文件,
    postFilesize: '' //选择文件的文件大小
  },

  // -methods---------------------------------------------------------------------------------------
  //封装函数-------------
  //获取时间 ，返回格式为 1991/1/1 12:30:12
  getNowDate() {
    var myDate = new Date();
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var hours = myDate.getHours(); //获取当前小时
    var minutes = myDate.getMinutes(); //获取当前分钟
    var seconds = myDate.getSeconds(); //获取当前秒
    var now = year + "/" + mon + "/" + date + " " + hours + ":" + minutes + ":" + seconds;
    return now;
  },
  //写入fileRecord表的封装函数
  async _uploadFilecollection() {
    let that = this;
    //写入fileRecord表
    const db = wx.cloud.database();
    const todos = db.collection('Users');
    console.log(this.data.willingFirst_index);
    console.log(this.data.willingSecond_index);
    var willingOne = this.data.willingFirst[this.data.willingFirst_index];
    var willingTwo = this.data.willingSecond[this.data.willingSecond_index];
    console.log(willingOne);
    console.log(willingTwo);
    var fileID = this.data.onlineFilepath;
    await db.collection('Willings').add({
        // data 字段表示需新增的 JSON 数据
        data: {
          _openid: app._openid,
          fileID: fileID,
          willing: [{
              departmentName: willingOne,
              admissionStatus: 0
            },
            {
              departmentName: willingTwo,
              admissionStatus: 0
              //0表示未处理
            }
          ],
          postTime: data_now,
          postFilename: this.data.postFilename,
          time: this.getNowDate(),
          postfileSize: this.data.postFilesize
        }
      })
      .then(result => {
        // console.log(res)
        //重置文件选中状态
        that._renewFilestatus()
        //跳转到面试群
        this._navigategroup();
      }).catch(error => {
        this._hideLoading();
        wx.showToast({
          title: '写入数据库出错',
          icon: 'error'
        })
      })
  },
  //重置选择文件状态
  _renewFilestatus() {
    this.setData({
      temperFilePath: '',
      willingFirst_index: '',
      willingSecond_index: ''
    })
  },
  //获取授权
  _accredit() {
    wx.requestSubscribeMessage({
      tmplIds: ['f8o5SBsIkZhkeembJWyF3nXF-CFwLGPqRWpWh-S-xZo'],
      success: (res) => {
        console.log("授权成功")
        console.log(res)
      },
      fail: (res) => {
        console.log("授权失败")
        console.log(res)
      }
    })
  },
  //加载弹窗
  _showLoading() {
    wx.showLoading({
      title: '正在努力加载……',
      mask: true
    })
  },
  //隐藏加载弹窗
  _hideLoading() {
    wx.hideLoading()
  },
  // ------------------------------------------------------------
  //删除文件
  _deleteFile() {
    const temperOnlinefileID = this.data.temperOnlinefileID
    //如果文件名不同，则需要先删除原来的文件
    wx.cloud.deleteFile({
      fileList: [temperOnlinefileID],
      success: res => {
        // handle success
        console.log("删除文件成功")
        console.log(res)
      },
      fail: err => {
        // handle error
        console.log("删除失败")
      },
      complete: res => {
        // ...
        console.log(temperOnlinefileID)
        console.log("有调用删除函数")
      }
    })
  },
  //跳转到报名成功，显示面试公告的界面
  _navigategroup() {
    console.log('test')
    wx.navigateTo({
      url: '../uploadSuccess/uploadSuccess?firstWilling=' + this.data.willingFirst_index + '&secondWilling=' + this.data.willingSecond_index,
    })

  },

  //部门投递数量统计,只会在第一次投递的时候调用
  _addDepartmentcount() {
    //1.判断是否已有记录
    //     1.1没有的话新增记录，并将num设置为1,
    //     1.2如果有的话则直接num+1即可
    console.log('部门数量统计被调用了');
    db.collection('departmentCount').where({
      year: data_now,
    }).update({
      data: {
        departments: {
          [this.data.willingFirstName]: _.inc(1)
        }
      },
      success: res => {
        console.log('增加部门数量');
        console.log(res);
        if (res.stats.updated == 0) {
          db.collection('departmentCount').add({
            data: {
              departments: {
                [this.data.willingFirstName]: 1
              },
              year: data_now
            },


          })
        }
        if (this.data.willingSecondName != '无') {
          db.collection('departmentCount').where({
            year: data_now
          }).update({
            data: {
              departments: {
                [this.data.willingSecondName]: _.inc(1)
              }
            },
            success: res => {
              console.log(res);
            }
          })
        }
      }
    })

  },
  // 自定义操作函数------------------------------------------------------------------------------------
  _ChoosewillingFirst: function (e) {
    // console.log(e);
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      willingFirst_index: e.detail.value,
      willingFirstName: this.data.willingFirst[e.detail.value],
      pickStatus_1: 'hidden'
    });
    console.log('第一志愿：' + this.data.willingFirst[this.data.willingFirst_index]);
  },
  _ChoosewillingSecond: function (e) {
    // console.log(e);
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    if (this.data.willingFirstName == this.data.willingSecond[e.detail.value]) {
      wx.showModal({
        title: '提示',
        content: "请不要选择两个相同的志愿",
        showCancel: false
      })
    } else {
      this.setData({
        willingSecond_index: e.detail.value,
        willingSecondName: this.data.willingSecond[e.detail.value],
        pickStatus_2: 'hidden'
      });
    }

    console.log('第二志愿：' + this.data.willingSecond[this.data.willingSecond_index]);
  },
  // 选择文件
  _chooseFile() {
    var that = this
    const systemInfo = wx.getDeviceInfo().system
    console.log(systemInfo)
    if (!that.isMobileOperatingSystem(systemInfo)) {
      getApp().showMessage("由于微信限制，电脑无法提取文件，请使用手机操作，给您带来了不便实在抱歉。")
      return;
    }
    wx.chooseMessageFile({
      count: 1,
      type: 'file',

      extension: ["pdf"],
      success: res => {
        console.log(res)
        this.setData({
          fileInfo: res.tempFiles[0]
        })
        const postFileName = res.tempFiles[0].name
        console.log(postFileName);
        const extensionName = extension.getExtensionName(postFileName)
        const postFilesize_string = String(res.tempFiles[0].size / 1024)
        const postFilesize = postFilesize_string.substring(0, postFilesize_string.indexOf('.')) + "KB"
        //判断文件是否合法
        if (extensionName == 'pdf') {
          //给名字加上时间戳
          var fileoldName = res.tempFiles[0].name
          // var splictName=fileoldName.substring(0,fileoldName.indexOf('.'))
          // res.tempFiles[0].name=splictName+Date.now()+'.pdf'
          res.tempFiles[0].name = Date.now() + res.tempFiles[0].name
          console.log(res.tempFiles[0].name);
          this.setData({
            temperFile: res.tempFiles[0],
            temperFilePath: res.tempFiles[0].path,
            extensionName: extensionName,
            postFilename: postFileName,
            postFilesize: postFilesize,
          })
          //文件名太长时加上省略号
          if (this.data.postFilename.length > 8) {
            var postFilenameModified = postFileName.slice(0, 8) + "..." + extensionName
            this.setData({
              postFilenameModified: postFilenameModified
            })
          } else {
            this.setData({
              postFilenameModified: this.data.postFilename
            })
          }
        } else {
          wx.showModal({
            content: '当前文件格式不合法,仅支持pdf文件',
            showCancel: false
          })
        }
      },
      fail: res => {
        wx.showToast({
          title: '请重新选择',
          icon: 'error'
        })
      }
    })
  },

  //预览文件
  _checkFile() {
    var temperFile = this.data.temperFile
    var temperFilePath = this.data.temperFilePath
    //判断是否已选择文件
    if (temperFilePath != '') {
      wx.openDocument({
        filePath: temperFilePath,
        fileType: 'pdf',
        showMenu: 'true',
        success: res => {
          console.log(res)
        },
        fail: res => {
          console.log(res)
        }
      })
    } else {
      wx.showToast({
        title: "你还没选择文件",
        icon: 'error',
        duration: 2000, //提示的延迟时间，单位毫秒，默认：1500 
        mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false 
        success: function () {},
        fail: function () {},
        complete: function () {}
      })
    }
  },

  sendEmail() {
    let that = this;
    wx.cloud.callFunction({
      name: 'sendEmailAfterDeliver',
      data: {
        realName: app.personInfo.realName,
        willingFirstName: that.data.willingFirstName,
        willingSecondName: that.data.willingSecondName
      },

    }).then(res => {
      console.log("发送投递邮件云函数请求成功");
      console.log(res);
    }).catch(res => {
      console.log("发送投递邮件云函数请求失败");
      console.log(res);
    })
  },

  //投递报名表逻辑.txt
  async _uploadFile() {
    const that = this;
    //判断是不是在投递时间范围内
    if(!await that.selectTime()){
      wx.showModal({
        title: '不在投递时间',
        content: '投递尚未开始或者投递时间已结束',
      })
      return;
    }
    wx.showModal({
      title: '确认投递',
      content: '请检查您在本小程序填写志愿的情况，保证其与您的报名表上的内容一致，以方便我们更好地获取您的志愿信息。',
      complete: async (res) => {
        if (res.cancel) {
          return;
        }
        if (res.confirm) {
          const files = this.data.temperFile; //文件名+一串数字
          const filespath = this.data.temperFilePath; //文件地址
          const willingFirst_index = this.data.willingFirst_index; //第一志愿对应的索引
          const willingSecond_index = this.data.willingSecond_index; //第二志愿对应的索引
          const extensionName = this.data.extensionName; //文件的扩展名

          //检查志愿信息
          //判断志愿信息是否完整
          if (willingFirst_index === '' || willingSecond_index === '' || parseInt(willingFirst_index) == 0) { //志愿信息不完整的两个情况：其中一个志愿为空或第一志愿为“请选择”
            wx.showToast({
              title: '请补齐志愿信息',
              icon: 'error'
            })
          } else {
            //修改志愿填写情况
            that.setData({
              willingStatus: true
            })
          }
          //检查文件信息
          //判断页面中是否选择文件
          if (filespath === '') {
            wx.showToast({
              title: '请选择文件',
              icon: 'error'
            })
          } else if (that.data.willingStatus) {
            const isOk=await that.updateFileAndWilling(filespath, getApp().data.userId, willingFirst_index, willingSecond_index)
            console.log(isOk)
            if(isOk)that._navigategroup() //跳转到面试公告页面
          }
        }
      }
    })

  },

  //将文件url和志愿信息传入数据库
  updateFileAndWilling(pdfUrl, userId, firstWilling, secondWilling) {
    console.log('第一志愿', firstWilling)
    console.log('第二志愿', secondWilling)

    return new Promise((reslove, reject) => {
      wx.uploadFile({
        filePath: pdfUrl,
        name: 'pdf',
        url: baseUrl + '/uploadpdf',
        formData: {
          firstWilling: firstWilling,
          secondWilling: secondWilling,
          userId: userId
        },
        success: (res) => {
          res.data=JSON.parse(res.data)
          if(res.data.code==2||res.data.code==3||res.data.code==1){
            wx.showModal({
              showCancel: false,
              title: '提示',
              content: '投递失败，请刷新小程序重新投递！若仍然无效，请联系管理员。',
          cancelColor: 'cancelColor',
            })
            reslove(false)
          }
          reslove(true)
        },
        fail:(err)=>{
          wx.showModal({
            showCancel: false,
            title: '提示',
            content: '投递失败，请刷新小程序！若仍然无效，请联系管理员。',
        cancelColor: 'cancelColor',
          })
          reslove(false)
        }
      })
    })
  },

  async checkIsopen() {
    var result = 1;
    await db.collection("uploadFilecontroler").get().then(res => {
      console.log(res);
      if (res.data[0].isOpen) {
        //修改
        console.log("修改result");
        result = 0;
      }
    })
    return result;
  },

  //判断系统是不是手机系统
  isMobileOperatingSystem(osString) {
    // 将操作系统字符串转换为小写，以便进行不区分大小写的比较  
    const lowerOsString = osString.toLowerCase();

    // 常见的移动操作系统名称，包括鸿蒙  
    const mobileOSNames = ['ios', 'android', 'windows phone', 'blackberry', 'symbian', 'harmonyos', '鸿蒙'];

    // 检查操作系统字符串是否包含任何移动操作系统名称  
    return mobileOSNames.some(name => lowerOsString.includes(name));
  },

  //判断是否在投递时间范围内
  selectTime() {
    //获取现在时间
    const now = new Date()
    const timestamp = now.getTime()
    //获取投递时间
    return new Promise((resolve, reject) => {
      wx.request({
        url: getApp().data.domain + '/getApplyTime',
        method: 'GET',
        success: (res) => {
          const data = res.data.data
          //转换内容
          if (timestamp >= data.startTime && timestamp <= data.endTime) {
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
    })
  },
  /**
   * 用户点击右上角分享
   */
  async onShow(){
    const isInfoEdited =await getApp().IsPersonalInfoEdit()
    if(!getApp().data.infoHaveEdited || !isInfoEdited){
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请先完善个人资料，以便您后续可以查询录取情况；如果本提示在编辑完资料后仍然出现，请尝试等待片刻并刷新小程序。',
        cancelColor: 'cancelColor',
        success: res => {
          if (res.confirm) {
            //点了确定
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }
        }
      })
    }
  },
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '广师大科教，了解一下？',
          imageUrl: '../../image/shareLogo.png'
        })
      }, 1000)
    })
    return {
      title: '广师大科教，了解一下？',
      path: "pages/uploadRegisterfile/uploadRegisterfile",
      promise
    }
  },

  onShareTimeline() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '广师大科教，了解一下？',
          imageUrl: '../../image/shareLogo.png'
        })
      }, 1000)
    })
    return {
      title: '广师大科教，了解一下？',
      promise
    }
  }
})

/*
  是哪个二货在中秋节还在加班敲代码呀？
  厚，原来是我QAQ
*/